package com.by.springbootbanner.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;

public class ImageToASCIIUtil {

    private static final String GRAY_STR = "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\\|()1{}[]?-_+~<>i!lI;:,\"^`'";
    private static final int DEFAULT_WIDTH = 100;

    public static String imageToASCII(InputStream input) {
        try {
            BufferedImage image = ImageIO.read(input);
            int width = image.getWidth();
            int height = image.getHeight();
            int scaleWidth = DEFAULT_WIDTH;
            int scaleHeight = height * DEFAULT_WIDTH / width;
            Image scaledInstance = image.getScaledInstance(scaleWidth, scaleHeight, Image.SCALE_DEFAULT);
            BufferedImage scaleImage = new BufferedImage(scaleWidth, scaleHeight, BufferedImage.TYPE_INT_RGB);
            Graphics graphics = scaleImage.getGraphics();
            graphics.drawImage(scaledInstance, 0, 0, null);
            graphics.dispose();
            StringBuilder result = new StringBuilder();
            for (int i = 0; i < scaleHeight; i++) {
                result.append("\n");
                for (int j = 0; j < scaleWidth; j++) {
                    int rgb = scaleImage.getRGB(j, i);
                    int grayValue = toGrayValue(rgb);
                    result.append(GRAY_STR.charAt((int) Math.ceil((GRAY_STR.length() - 1) * grayValue / 255)));
                }
            }
            return result.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static int toGrayValue(int rgb) {
        int r = (rgb & 0xFF0000) >> 16;
        int g = (rgb & 0x00FF00) >> 8;
        int b = (rgb & 0x0000FF);
        return (int) (0.21 * r + 0.72 * g + 0.07 * b);
    }

}
